package com.nnnu.wsnackshop.service.impl;

import com.nnnu.wsnackshop.pojo.entity.Favorites;
import com.nnnu.wsnackshop.mapper.FavoritesMapper;
import com.nnnu.wsnackshop.service.IFavoritesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

import java.time.LocalDateTime;

/**
 * <p>
 * 收藏 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Service
@RequiredArgsConstructor
public class FavoritesServiceImpl extends ServiceImpl<FavoritesMapper, Favorites> implements IFavoritesService {

    @Override
    public Boolean checkFavorite(Integer userId, Integer productId) {
        LambdaQueryWrapper<Favorites> qw = Wrappers.<Favorites>lambdaQuery()
                .eq(Favorites::getUserId, userId)
                .eq(Favorites::getProductId, productId);
        Long count = baseMapper.selectCount(qw);
        return count > 0;
    }

    @Override
    public void addFavorite(Integer userId, Integer productId) {
        // 检查是否已经收藏，避免重复添加
        if (checkFavorite(userId, productId)) {
            return;
        }
        Favorites favorite = new Favorites();
        favorite.setUserId(userId);
        favorite.setProductId(productId);
        favorite.setAddedAt(LocalDateTime.now());
        baseMapper.insert(favorite);
    }

    @Override
    public void removeFavorite(Integer userId, Integer productId) {
        LambdaQueryWrapper<Favorites> qw = Wrappers.<Favorites>lambdaQuery()
                .eq(Favorites::getUserId, userId)
                .eq(Favorites::getProductId, productId);
        baseMapper.delete(qw);
    }
}
